//
//  FriendViewController.m
//  map
//
//  Created by dllo on 16/4/25.
//  Copyright © 2016年 王彦森. All rights reserved.
//

#import "FriendViewController.h"
#import "AddViewController.h"
#import "ChatPersonViewController.h"
#import "EaseMob.h"
#import "BlockNameTableViewCell.h"
@interface FriendViewController ()<UITableViewDataSource,UITableViewDelegate,EMChatManagerDelegate>
@property(nonatomic,strong)UIButton *clearBut;
@property(nonatomic,strong)UIButton *addBut;
@property(nonatomic,strong)UITableView *tableView;
@property(nonatomic,strong)NSMutableArray *listArr;
@property(nonatomic,assign)NSInteger indexRow;
@property(nonatomic,strong)UITableView *BlockTableView;//群组的tableView
@property(nonatomic,strong)NSMutableArray *BlockArr;//群组的数组
@end

@implementation FriendViewController

-(void)loadView{
    [super loadView];
    
 [[EaseMob sharedInstance].chatManager asyncFetchBuddyListWithCompletion:^(NSArray *buddyList, EMError *error) {
     if (!error) {
         NSLog(@"获取成功--%@",buddyList);
         [_listArr removeAllObjects];
         [_listArr addObjectsFromArray:buddyList];
         [_tableView reloadData];
        
     }
     
     
 } onQueue:dispatch_get_main_queue()];
    
    
    [[EaseMob sharedInstance].chatManager asyncFetchBlockedListWithCompletion:^(NSArray *blockedList, EMError *error) {
        NSLog(@"=黑名单的列表%@=",blockedList);
        [_BlockArr removeAllObjects];
        [_BlockArr addObjectsFromArray:blockedList];
        [_BlockTableView reloadData];
        
    } onQueue:nil];
    
  }

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    self.clearBut = [UIButton buttonWithType:UIButtonTypeSystem];
    [self.clearBut setTitle:@"注销" forState:UIControlStateNormal];
    [self.clearBut addTarget:self action:@selector(clear:) forControlEvents:UIControlEventTouchUpInside];
    self.clearBut.frame = CGRectMake(10, 10, 60, 40);
    [self.view addSubview:self.clearBut];
    
    self.addBut =[UIButton buttonWithType:UIButtonTypeSystem];
    self.addBut.frame = CGRectMake(self.view.frame.size.width - 80, 10, 60, 40);
    [self.addBut setTitle:@"添加" forState:UIControlStateNormal];
    [self.addBut addTarget:self action:@selector(add:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.addBut];
    
    self.listArr = [NSMutableArray array];
    
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(self.view.frame.size.width/3, 50, self.view.frame.size.width/3*2, self.view.frame.size.height-60)];
    self.tableView.backgroundColor = [UIColor yellowColor];
    self.tableView.delegate =self;
    self.tableView.dataSource = self;
    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"reuse"];
    [self.view addSubview:self.tableView];
    
    //签代理
    [[EaseMob sharedInstance].chatManager  addDelegate:self delegateQueue:nil];

    self.BlockTableView = [[UITableView alloc]initWithFrame:CGRectMake(0,50, self.view.frame.size.width/3, self.view.frame.size.height-60)];
    self.BlockTableView.delegate =self;
    self.BlockTableView.dataSource = self;
    [self.BlockTableView registerClass:[BlockNameTableViewCell class] forCellReuseIdentifier:@"group"];
    [self.view addSubview:self.BlockTableView];
    self.BlockArr = [NSMutableArray array];
    //创建群组
    [self createGroup];
}

-(void)createGroup{
//    EMGroupStyleSetting *groupStyleSetting=[[EMGroupStyleSetting alloc]init];
//    groupStyleSetting.groupMaxUsersCount = 30;//设置群员的个数,默认为200
//    groupStyleSetting.groupStyle = eGroupStyle_PublicOpenJoin;//创建不同类型的群组
//    
//    
//    //参数1:群组的名字
//    //参数2:群组的描述
//    //参数3:群组的成员
//    //
////    NSArray *Arr = self.groupArr;
//   [[EaseMob sharedInstance].chatManager asyncCreateGroupWithSubject:@"好难" description:@"真的好难" invitees: @[@"00"] initialWelcomeMessage:@"不知道奥" styleSetting:groupStyleSetting completion:^(EMGroup *group, EMError *error) {
//       
//   } onQueue:dispatch_get_main_queue()];
}


#pragma mark 回调监听
-(void)group:(EMGroup *)group didCreateWithError:(EMError *)error{
    if (!error) {
        NSLog(@"群组的名字:%@ 创建成功",group);
        
    }else{
        NSLog(@"====失败的原因:%@",error);
    }

}

//注销,退出当前的用户
-(void)clear:(UIButton*)but{
   
    /*!
     @method
     @brief 异步方法, 注销当前登录用户
     @discussion 当接收到【didLoginFromOtherDevice】和【didRemovedFromServer】的回调时，调用此方法，isUnbind传NO
     @result 完成后【didLogoffWithError:】回调会被触发.
     */
    [[EaseMob sharedInstance].chatManager asyncLogoffWithUnbindDeviceToken:YES];
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
}

-(void)add:(UIButton*)add{

    AddViewController *addVc = [[AddViewController alloc]init];
[self presentViewController:addVc animated:YES completion:^{
    
}];
}


-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (self.tableView == tableView) {
          return self.listArr.count;
    }else{
        return self.BlockArr.count;
        
    }
    

}
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (tableView == self.tableView) {
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"reuse" forIndexPath:indexPath];
//        EMBuddy *buddy = self.listArr[indexPath.row];
        id a = self.listArr[indexPath.row];
        if ([a isKindOfClass:[EMBuddy class]]) {
            EMBuddy *buddy = a;
            cell.textLabel.text = buddy.username;
        }else{
            cell.textLabel.text =a;
        }
        return cell;
    }else{
        BlockNameTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"group" forIndexPath:indexPath];
        cell.name.text = self.BlockArr[indexPath.row];
        return cell;
    }
}

/*!
 @method
 @brief 接收到好友请求时的通知
 @discussion
 @param username 发起好友请求的用户username
 @param message  收到好友请求时的say hello消息
 */
-(void)didReceiveBuddyRequest:(NSString *)username message:(NSString *)message{
    
    //提示框
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:[NSString stringWithFormat:@"收到来自%@的请求",username] message:message preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *acction = [UIAlertAction actionWithTitle:@"好" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        EMError *error ;
        /*!
         @method
         @brief 接受某个好友发送的好友请求
         @discussion
         @param username 需要接受的好友username
         @param pError   错误信息
         @result 是否接受成功
         */
        if ([[EaseMob sharedInstance].chatManager acceptBuddyRequest:username error:&error]&&!error) {
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3*NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                //获取好友的列表内的元素
               [ [EaseMob sharedInstance].chatManager asyncFetchBlockedListWithCompletion:^(NSArray *blockedList, EMError *error) {
                   NSLog(@"blockList:获取成功%@",blockedList);
                   
                   [self.listArr removeAllObjects];
                   
                   [self.listArr addObjectsFromArray:blockedList];
                   [self loadBuddyListFromServer];
//                   [_tableView reloadData];
                   #warning buddyList的个数,仍然是没有添加好友之前的个数,从服务器获取

                } onQueue:dispatch_get_main_queue()];
            });
        }
    }];

UIAlertAction *rejecAction = [UIAlertAction actionWithTitle:@"不要" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
    EMError *error;
    if ([[EaseMob sharedInstance].chatManager rejectBuddyRequest:username reason:@"俺不认识你" error:&error]&&!error) {
             NSLog(@"发送拒绝成功");
    }
}];
    [alert addAction:acction];
    [alert addAction:rejecAction];
    [self showViewController:alert sender:nil];
    
    
}



#pragma mark 从服务器获取好友列表
-(void)loadBuddyListFromServer{

[[EaseMob sharedInstance].chatManager asyncFetchBuddyListWithCompletion:^(NSArray *buddyList, EMError *error) {
    
    NSLog(@"从服务器上获取好友的列表%@",buddyList);
    [self.listArr removeAllObjects];
    //赋值数据源
    [self.listArr addObjectsFromArray:buddyList];
    //刷新
    [self.tableView reloadData];

} onQueue:dispatch_get_main_queue()];
    


}

#pragma mark 从服务器上获取黑名单列表
-(void)refreshBlockData{

    ///获取黑名单的数据
    [[EaseMob sharedInstance].chatManager asyncFetchBlockedListWithCompletion:^(NSArray *blockedList, EMError *error) {
//        self.BlockArr = [blockedList copy];
        [self.BlockArr removeAllObjects];
        [self.BlockArr addObjectsFromArray:blockedList];
        
        [self.BlockTableView reloadData];
    } onQueue:nil];

}

#pragma Mark 好友列表数据刷新
-(void)didUpdateBuddyList:(NSArray *)buddyList changedBuddies:(NSArray *)changedBuddies isAdd:(BOOL)isAdd{
    NSLog(@"好友列表数据被更新 %@",buddyList);
    [self.listArr removeAllObjects];
    [self.listArr addObjectsFromArray:buddyList];
    NSLog(@"=+=%@",self.listArr);
}

#pragma mark 删除好友
-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{    
    if (tableView == self.tableView) {
        if (editingStyle == UITableViewCellEditingStyleDelete) {
            EMBuddy *buddy = self.listArr[indexPath.row] ;
            [[EaseMob sharedInstance].chatManager removeBuddy: buddy.username removeFromRemote:YES error:nil];
            
            [self.listArr removeObjectAtIndex:indexPath.row];
//            [self loadBuddyListFromServer];
            [self.tableView reloadData];
            
        }
    }else{
    
        NSLog(@"11");
    }
    
   
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (tableView == self.tableView) {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"这是一个艰难的选择,是否将他加入黑名单,如何选择取消这回跳转到对话界面" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *alertTitle  = [UIAlertAction actionWithTitle:@"好的" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            EMBuddy *buddy = self.listArr[indexPath.row];
            NSLog(@"buddy:::%@",buddy);
            EMError *error = [[EaseMob sharedInstance].chatManager blockBuddy:buddy.username relationship:eRelationshipBoth];
            if(!error){
                NSLog(@"发送成功");
                [[EaseMob sharedInstance].chatManager removeBuddy: buddy.username  removeFromRemote:YES error:nil];
                [self.listArr removeObject:self.listArr[indexPath.row]];
                [self.BlockTableView reloadData];
                   [self loadBuddyListFromServer];
                [self.tableView reloadData];
             
                [self refreshBlockData];
            }else{
                NSLog(@"添加黑名单错误的原因:%@",error);
            }
            
        }];
        
        UIAlertAction *alertmessager = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            ChatPersonViewController *chat = [[ChatPersonViewController alloc]init];
            EMBuddy *buddy = _listArr[indexPath.row];
            chat.name = buddy.username;
            [self presentViewController:chat animated:YES completion:nil];
            
        }];
        [alert addAction:alertTitle];
        [alert addAction:alertmessager];
        [self presentViewController:alert animated:YES completion:nil];

    }else{
        
        ///移除黑名单
        UIAlertController *alertTion = [UIAlertController alertControllerWithTitle:@"提示" message:@"是否将他放出来" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *done = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            EMError *error = [[EaseMob sharedInstance].chatManager unblockBuddy:self.BlockArr[indexPath.row]];
            if (!error) {
                NSLog(@"黑名单移除发送成功");
                [[EaseMob sharedInstance].chatManager removeBuddy:self.BlockArr[indexPath.row] removeFromRemote:YES error:nil];
                NSString *str = self.BlockArr[indexPath.row];
               
//                NSMutableArray *arr = [NSMutableArray arrayWithObject:self.BlockArr];
//                
//                [arr removeObject:str];
//                
//                self.BlockArr = [NSMutableArray copy];
//                NSArray *dataArr = arr;
//                NSLog(@"====%@",dataArr);
//                arr = [NSArray copy];
//                [self.BlockArr addObjectsFromArray:arr];
                
                [self.BlockArr removeObject:str];
                [self.BlockTableView reloadData];
            }else{
                NSLog(@"失败的原因:%@",error);
            }
        }];
        
        UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:0 handler:^(UIAlertAction * _Nonnull action) {
        
        }];
        
        [alertTion addAction:done];
        [alertTion addAction:cancel];
        [self presentViewController:alertTion animated:YES completion:nil];
    }
    
   }

///移除黑名单的方法回调
- (void)didUnblockBuddy:(EMBuddy *)buddy error:(EMError *)pError{
    NSLog(@"移出的黑名单:%@",buddy.username);

}

/*!
 @method
 @brief 好友黑名单有更新时的回调
 @discussion
 @param blockedList 被加入黑名单的好友的列表
 */
- (void)didUpdateBlockedList:(NSArray *)blockedList{



}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
